<template>
<!--  <h2>自定义统计</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true">
      <el-form-item label="日期">
        <el-date-picker style="width: 240px" v-model="daterange" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item label="门类">
        <!-- <el-select v-model="queryParams.categoryId" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="item in categoryIdOption" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select> -->

        <treeselect v-model="queryParams.categoryId" :options="categoryIdOption" :disable-branch-nodes="true" label
                            placeholder="请选择档案门类" noOptionsText="暂无数据" :normalizer="normalizerCategoryID"
                            :style="isStyle ? 'line-height: 32px;font-size:12px' : 'line-height: 36px;font-size:14px'" style="width: 240px"/>
      </el-form-item>

      <el-form-item label="归档单位">
        <treeselect v-model="queryParams.deptId" :options="optionSelect" :show-count="true" placeholder="请选择归属部门" style="width:240px;" :normalizer="normalizer"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-s-data"  @click="count">统计</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-rank"  @click="xAxis">x轴</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-rank"  @click="yAxis">y轴</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-s-data"  @click="statisticalContent">统计内容</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download"  @click="exportExcel" v-show="isShowTable">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-printer"  @click="print" v-show="isShowTable">打印</el-button>
      </el-col>
    </el-row>
    <div style="width: 80%; margin: 0 auto;" v-show="isShowTable">
      <!-- 人员名称的table -->
      <div v-show="xRadio=='4'">
        <div class="box">
          <table class="custom-table">
            <thead>
            <tr class="title">
              <th :colspan="2" style="border: 0 !important;">
                <h1 style="font-size: 28px;" class="h1">
                  自定义统计
                </h1>
              </th>
            </tr>
            <tr>
              <th>人员名称</th>
              <th>访问次数</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>{{ item.USER_NAME }}</td>
              <td>{{ item.USER_COUNT }}</td>
            </tr>
            </tbody>
          </table>
          <div style="width: 70%; height: 300px; margin: 0 auto; margin-top: 3%">
            <div id="histogram" style="width: 90%; height:100%;"></div>
          </div>
        </div>
      </div>
      <!-- y轴没选的table -->
      <div v-if="xRadio != '4' && yRadio == undefined">
        <div class="box1">
          <table class="custom-table1">
            <thead>
            <tr class="title">
              <th :colspan="detail.length + 1" style="border: 0 !important;">
                <h1 style="font-size: 28px;" class="h1">
                  自定义统计
                </h1>
              </th>
            </tr>
            <tr>
              <th class="row-0" style="width:150px;height:50px;">
                <div class="biaotou">{{ xiazi }}</div>
              </th>
              <th v-for="item in detail" :key="item">{{item.label}}</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>{{ item.NAME }}</td>
              <td v-for="column in detail" :key="column">{{ item[column.value] }}</td>
            </tr>
            </tbody>
          </table>
          <div style="width: 70%; height: 300px; margin: 0 auto; margin-top: 3%">
            <div id="histogram1" style="width: 90%; height:100%;"></div>
          </div>
        </div>
      </div>
      <!-- x,y都选择 -->
      <div v-if="yRadio != undefined">
        <div class="box2">
          <table class="custom-table2">
            <thead>
            <tr class="title">
              <th :colspan="detail.length * rowdata.length + 1" style="border: 0 !important;">
                <h1 style="font-size: 28px;" class="h1">
                  自定义统计
                </h1>
              </th>
            </tr>
            <tr>
              <th rowspan="2" style="position: relative; min-width: 70px">
                <span class="span1">{{ xiazi }}</span>
                <span class="span2">{{ shangzi }}</span>
              </th>
              <th :colspan="detail.length" v-for="item in rowdata" :key="item">{{item.label}}</th>
            </tr>
            <tr>
               <template v-for="row in rowdata">
                <th v-for="item in detail" :key="item">{{ item.label }}</th>
               </template>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>
                <div v-if="xRadio=='1'">{{item.ND}}</div>
                <div v-if="xRadio=='2'">{{item.DEPT_NAME}}</div>
                <div v-if="xRadio=='3'">{{item.NAME}}</div>
              </td>
              <td v-for="column in row" :key="column">{{ item[column] }}</td>
            </tr>
            </tbody>
          </table>
          <div style="width: 70%; height: 300px; margin: 0 auto; margin-top: 3%" v-for="(item, index) in detail.length " :key="item">
            <div :id="'histogram2' + index" style="width:90%; height:100%;"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 选择x轴/y轴字段弹窗 -->
    <AxisSelection :title="title" :open="open" :axisType="axisType" @cancel="cancel" @getXdata="getXdata" ref="axisRef" @getYdata="getYdata"></AxisSelection>

    <!-- 选择统计内容 -->
    <StatisticsSelection :open="selectOpen" :radio="xRadio" @cancel="cancel" @getNeiRong="getNeiRong" ref="statRef"></StatisticsSelection>
  </div>
</template>

<script>

import {deptTreeSelect} from "@/api/system/user";
import {getcategory, getdatatable} from "@/api/archive/statistics/customizeStatistics/customizeStatistics";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AxisSelection from "@/views/archive/statistics/customizeStatistics/axisSelection";
import StatisticsSelection from "@/views/archive/statistics/customizeStatistics/statisticsSelection";
import * as XLSX from "xlsx";
import * as echarts from "echarts";
import { listGROUPTree } from "@/api/archive/archivalAppraisal/openness/openArchivesAppraisal"//档案门类树
export default {
  name: "index",
  components: {StatisticsSelection, AxisSelection, Treeselect },
  data() {
    return {
      queryParams: {
        startTime: undefined,
        endTime: undefined,
        categoryId: undefined,
        deptId: undefined
      },
      daterange: [],
      optionSelect: [],
      categoryIdOption: [],

      // 选择轴弹窗
      title: '',
      open: false,
      axisType: '',
      // x轴数据
      x: undefined,
      // y轴数据
      y: undefined,
      // 统计内容
      neirong: undefined,
      // x轴选择数据
      xRadio: undefined,
      // y轴选择数据
      yRadio: undefined,
      // 统计内容弹窗
      selectOpen: false,
      // table表格
      shangzi: undefined,
      xiazi: undefined,

      //是否展示表格
      isShowTable: false,
      // 表头
      rowdata: [],
      // 统计内容
      detail: [],
      // 表格数据
      tableData: [],
      // 行数据
      row: [],

      dataUrl: '',
      dataUrls: []
    }
  },
  created() {
    this.deptTreeSelectPost()
    this.getCategoryId()
    if (this.$store.getters.size == 'small') {

this.isStyle = true

} else {

this.isStyle = false
}
  },
  methods: {
              // 只能选择数据下面有children 的数据，没有children的时候禁用
              normalizerCategoryID(node) {
            if (node.nodeType == 'fonds') {
                if (node.children == undefined || node.children == null || !node.children.length) {

                    node['isDisabled'] = true;
                }

            }
            if (node.children == null || node.children == undefined || !node.children.length) {
                delete node.children;
            }
            return node
        },
      // 只能选择数据下面有children 的数据，没有children的时候禁用
      normalizer(node) {
            if (node.children == null || node.children == undefined || !node.children.length) {
                delete node.children;
            }
            return node
        },
    handleEndYearChange() {
      if(this.queryParams.endTime < this.queryParams.startTime) {
        this.queryParams.endTime = this.queryParams.startTime;
      }
      if (!this.queryParams.startTime) {
        this.queryParams.startTime = this.queryParams.endTime;
      }
    },
    //部门（单选）
    deptTreeSelectPost() {
      deptTreeSelect().then(response => {
        this.optionSelect = response.data;
      })
    },
    // 门类
    getCategoryId() {
      listGROUPTree().then(response => {
        this.categoryIdOption = response.data
      })
    },
    // 统计
    count() {
      this.tableData = []
      if(this.x == undefined) {
        this.$modal.msgWarning("请选择X轴字段!")
        return;
      }
      /*if(this.y == undefined) {
        this.$modal.msgWarning("请选择Y轴字段!")
        return;
      }*/
      if(this.neirong == undefined) {
        this.$modal.msgWarning("请选择统计内容!")
        return;
      }
      var xiazi=this.x.split(",")[0];
      if (xiazi == 'bgqx'){
        this.xiazi="保管期限";
      }else if (xiazi == 'dept'){
        this.xiazi="部门";
      }else if (xiazi == 'category'){
        this.xiazi="门类";
      }else{
        this.xiazi="年度";
      }
      if(xiazi!='role' && this.y != undefined){
        var shangzi=this.y.split(",")[0];
        if(shangzi == 'bgqx'){
          this.shangzi="保管期限";
        }else{
          this.shangzi="密级";
        }
        var y = this.y.split(',').splice(1).map(function(item) {
          return item.split('#')[0];
        });
        var detail = this.neirong.split(',').map(function(item) {
          return item.split('#')[0];
        });
        this.row = []
        for (let i = 0; i < y.length; i++) {
          for (let j = 0; j < detail.length; j++) {
            this.row.push(y[i]+detail[j])
          }
        }
      }
      if(this.daterange != null) {
        if (this.daterange.length != 0) {
          this.queryParams.startTime = this.daterange[0].toString()
          this.queryParams.endTime = this.daterange[1].toString()
        }
      } else {
        this.queryParams.startTime = undefined
        this.queryParams.endTime = undefined
      }
      this.getList()
      this.isShowTable = true
    },
    // 获取列表数据
    getList() {
      this.form = {
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        category: this.queryParams.categoryId,
        dept: this.queryParams.deptId,
        x: this.x,
        y: this.y,
        neirong: this.neirong
      }

      console.log(this.form,"------------------")
      getdatatable(this.form).then(response=>{
        this.tableData = response.data.data.map(item => {
          // 遍历每个对象的属性
          for (let key in item) {
            // 如果属性值为null或undefined，则替换为0
            if (item[key] === null || item[key] === undefined) {
              item[key] = "0";
            }
          }
          return item;
        });
        this.getHistogram()
      })
    },
    // 获取柱状图
    getHistogram() {
      // 人员是二维
      var xshow = '', xziduan='',yshow = '',xziduan='',nrshow = '',nrziduan='',twodx=[];
      if(this.xRadio=='4') {
        var passdata=[];
        for(var i=0;i<this.tableData.length;i++){
          twodx.push(this.tableData[i].USER_NAME);
          passdata.push(this.tableData[i].USER_COUNT);
        }
        xziduan=xziduan.substring(0, xziduan.lastIndexOf(","));
        this.drawRole("histogram",twodx,passdata)
      } else if(this.xRadio != '4' && this.yRadio == undefined) {
        //处理内容
        var nn = '';
        var nz='';
        var ns = this.neirong.toString().split(",");
        for (var i = 0; i < ns.length; i++) {
          nn += ns[i].split("#")[1] + ',';
          nz += ns[i].split("#")[0] + ',';
        }
        nrshow = nn.substring(0, nn.lastIndexOf(","));
        nrziduan=nz.substring(0, nz.lastIndexOf(","));
        var twodxs = [];
        var passdatas = [];
        var names = [];
        for (var i = 0; i < nrshow.toString().split(",").length; i++) {
          //var twodx1=[];
          var passdata=[];
          for(var j=0;j<this.tableData.length;j++){//遍历x
            if(i==0) {
              twodxs.push(this.tableData[j].NAME);
            }
            var v = this.tableData[j][nrziduan.toString().split(",")[i]];
            if(v==null || v=='') {
              v = "0";
            }
            passdata.push(v);
          }
          passdatas.push(passdata);
          names.push(nrshow.toString().split(",")[i]);
        }
        this.draw2d("histogram1", twodxs,passdatas,names);
      } else if(this.yRadio != undefined) {
        //处理X轴
        //年度需要处理成和其他一致:2020#2020,2021#2021
        if ('year' == this.x.toString().split(",")[0]) {
          var n = '';
          for (var i = 0; i < this.x.toString().split(",")[1].split("#")[1]; i++) {
            n += (parseInt(this.x.toString().split(",")[1].split("#")[0]) + i) + ",";
          }
          xziduan=n.substring(0, n.lastIndexOf(","));
        } else {
          var n = '';
          var nz='';
          var xs = this.x.replace(this.x.toString().split(",")[0] + ",", "");
          var xss = xs.split(",");
          for (var i = 0; i < xss.length; i++) {
            nz += xss[i].split("#")[0] + ',';
          }
          xziduan=nz.substring(0, nz.lastIndexOf(","));
        }
        var nz='';
        for(var i=0;i<this.tableData.length;i++){
          if('year' == this.x.toString().split(",")[0]){
            nz +=this.tableData[i].ND+ ',';
          }else if('dept' == this.x.toString().split(",")[0]){
            nz +=this.tableData[i].DEPT_NAME+ ',';
          }else if('category'== this.x.toString().split(",")[0]){
            nz +=this.tableData[i].NAME+ ',';
          }
        }
        xshow=nz.substring(0, nz.lastIndexOf(","));
        //处理Y轴
        var yy = '';
        var yyz='';
        var ys = this.y.replace(this.y.toString().split(",")[0] + ",", "");
        var yss = ys.split(",");
        for (var i = 0; i < yss.length; i++) {
          yy += yss[i].split("#")[1] + ',';
          yyz+=yss[i].split("#")[0] + ',';
        }
        yshow = yy.substring(0, yy.lastIndexOf(","));
        var yziduan = yyz.substring(0, yyz.lastIndexOf(","));
        //处理内容
        var nn = '';
        var nz='';
        var ns = this.neirong.toString().split(",");
        for (var i = 0; i < ns.length; i++) {
          nn += ns[i].split("#")[1] + ',';
          nz += ns[i].split("#")[0] + ',';
        }
        nrshow = nn.substring(0, nn.lastIndexOf(","));
        nrziduan=nz.substring(0, nz.lastIndexOf(","));
        let count = 0
        for (var i = 0; i < nrshow.toString().split(",").length; i++) {
          var passdata=[];
          for(var j=0;j<xshow.split(",").length;j++){//遍历x
            for(var k=0;k<yziduan.split(",").length;k++){//遍历y
              var xyz=[];
              xyz.push(k);
              xyz.push(j);
              let zz=(yziduan.split(",")[k]+nrziduan.split(",")[i]).toString();
              var d=this.tableData[j][zz];
              if(''==d||null==d||'null'==d){
                d='0';
              }
              xyz.push(d);
              passdata.push(xyz);
              console.log(123)
            }
            count ++
          }
          this.draw3d("histogram2" + i, xshow, yshow, nrshow.split(",")[i],passdata, count);
        }
      }
    },
    // 绘制柱状图
    drawRole(id,xziduan,passdata) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          show: 'true',
          text: '人员访问次数'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis:[ {
          type: 'category',
          data: xziduan,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value'
        }],
        series: [{
          data: passdata,
          type: 'bar'
        }]
      };

      option && myChart.setOption(option);
      myChart.on('finished', () => {
        this.dataUrl = myChart.getDataURL();
      });
    },
    // 2维图
    draw2d(id,xziduans,passdatas,names) {
      var varPassdatas = passdatas;
      var varXziduans = xziduans;

      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);

      var option = {
        title: {
          show: 'true',
          text: name
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'cross'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '20%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: names
        },
        xAxis:[ {
          type: 'category',
          data: xziduans,
          axisTick: {
            alignWithLabel: true,
            //type:'shadow'
          }
        }],
        yAxis: [],
        series: []
      };


      var yAxis = option.yAxis;
      var series = option.series;

      var sel = '';

      for(var i=0;i<names.length;i++) {
        sel += '<option value="'+i+'#'+(names[i])+'">'+(names[i])+'</option>';
        //passdatas
        //names
        var y = {
          type:'value',
          name:names[i],
          position:'right',
          offset: i*80,
          axisLine:{
            show:true
          }
          //axisLabel:
        };
        yAxis.push(y);
        var s = {
          name:names[i],
          type:'bar',
          yAxisIndex:[i],
          data:passdatas[i]
        }
        series.push(s);
      }

      $("#selectMain").html("");
      $("#selectMain").append(sel);

      option.yAxis = yAxis;
      option.series = series;

      var bs = {
          name: names[0],
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '20',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
          ]
        }

      var bsData = bs.data;
      for(var j=0;j<xziduans.length;j++) {
        var v = {
          value:passdatas[0][j],
          name:xziduans[j]
        };
        bsData.push(v);
      }
      bs.data = bsData;

      option && myChart.setOption(option);

      myChart.on('finished', () => {
        this.dataUrl = myChart.getDataURL();
      });
    },
    // 3维图
    draw3d(id, x, y, neirong,passdata, count) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      var option;

      var hours = x.toString().split(",");
      var days = y.toString().split(",");

      var data=passdata;
      option = {
        title: {
          show: 'true',
          text: neirong
        },
        tooltip: {
          formatter: function(p) {
            //console.log(p.data.value)
            return "X : "+x.split(",")[p.value[0]]+"<br />Y : "+y.split(",")[p.value[1]]+"<br />Z : "+p.value[2];
          }
        },
        visualMap: {
          max: 20,
          inRange: {
            color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
          }
        },
        xAxis3D: {
          type: 'category',
          data: hours
        },
        yAxis3D: {
          type: 'category',
          data: days
        },
        zAxis3D: {
          type: 'value'
        },
        grid3D: {
          boxWidth: 200,
          boxDepth: 80,
          viewControl: {
            // projection: 'orthographic'
          },
          light: {
            main: {
              intensity: 1.2,
              shadow: true
            },
            ambient: {
              intensity: 0.3
            }
          }
        },
        series: [{
          type: 'bar3D',
          data: data.map(function(item) {
            return {
              value: [item[1], item[0], item[2]],
            }
          }),
          shading: 'lambert',

          label: {
            fontSize: 16,
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 20,
              color: '#900'
            },
            itemStyle: {
              color: '#900'
            }
          }
        }]
      }

      option && myChart.setOption(option);
      myChart.on('finished', () => {
        let dataUrlObj = this.dataUrls.find(item => item.count == count);
        if(dataUrlObj) {
          // 找到count相同的对象,替换dataUrl
          dataUrlObj.dataUrl = myChart.getDataURL();
        } else {
          // 没找到count相同的对象,push新对象
          this.dataUrls.push({
            count: count,
            dataUrl: myChart.getDataURL()
          });
        }
      });
    },
    // 点击x轴
    xAxis() {
      this.isShowTable = false
      this.axisType = 'x'
      this.title = '选择x轴字段'
      this.open = true
      this.neirong = undefined
      this.yRadio = undefined
      this.y = undefined
      if(this.xRadio != undefined) {
        this.$nextTick(() => {
          this.$refs.axisRef.init(this.xRadio, this.x)
        })
      }
    },
    // 点击y轴
    yAxis() {
      this.isShowTable = false
      if(this.xRadio == '4') {
        this.$message({ message: '人员只能统计访问次数! 请在统计内容中选择访问次数', type: 'warning'})
        return;
      }
      this.axisType = 'y'
      this.title = '选择y轴字段'
      this.open = true
      this.neirong = undefined
      if(this.yRadio != undefined) {
        this.$nextTick(() => {
          this.$refs.axisRef.init(this.yRadio, this.y)
        })
      }
    },
    // 统计内容
    statisticalContent() {
      this.isShowTable = false
      if(this.x == undefined) {
        this.$modal.msgWarning("请选择x轴数据")
        return;
      }
      if (this.neirong != undefined) {
        this.$nextTick(() => {
          this.$refs.statRef.init(this.neirong)
        })
      }
      this.selectOpen = true
    },
    cancel() {
      this.open = false
      this.selectOpen = false
      this.axisType = ''
    },
    // 获取x轴数据
    getXdata(radio,data) {
      this.xRadio = radio
      this.x = data
      this.open = false
      this.neirong = undefined
      this.yRadio = undefined
      this.y = undefined
    },
    // 获取y轴数据
    getYdata(radio,data,length) {
      this.yRadio = radio
      this.y = data
      this.rowdata = length
      this.open = false
      this.neirong = undefined
    },
    // 获取统计内容
    getNeiRong(data) {
      this.neirong = data
      var arr = data.split(",")
      var result = arr.map(item => {
        return {
          value: item.split('#')[0],
          label: item.split('#')[1]
        };
      });
      this.detail = result
      this.selectOpen = false
    },
    // 导出
    exportExcel() {
      if(this.xRadio=='4') {
        const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table'));
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        console.log(worksheet)
        const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
        this.saveAsExcel(excelBuffer, `自定义统计_${new Date().getTime()}`);
      }else if(this.xRadio != '4' && this.yRadio == undefined) {
        const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table1'));
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        console.log(worksheet)
        const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
        this.saveAsExcel(excelBuffer, `自定义统计_${new Date().getTime()}`);
      } else if(this.yRadio != undefined) {
        const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table2'));
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        console.log(worksheet)
        const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
        this.saveAsExcel(excelBuffer, `自定义统计_${new Date().getTime()}`);
      }
    },
    saveAsExcel(buffer, filename) {
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${filename}.xlsx`;
      link.click();
    },
    // 打印
    print() {
      var iframeDoc;
      var boxElement;
      if(this.xRadio=='4') {
        boxElement = document.querySelector('.custom-table');
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        iframeDoc = iframe.contentWindow.document;
      } else if(this.xRadio != '4' && this.yRadio == undefined){
        boxElement = document.querySelector('.custom-table1');
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        iframeDoc = iframe.contentWindow.document;
      } else if(this.yRadio != undefined) {
        boxElement = document.querySelector('.custom-table2');
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        iframeDoc = iframe.contentWindow.document;
      }

      iframeDoc.open();
      iframeDoc.write(`
          <html>
          <head>
            <style>
              @media print {
                .custom-table {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table1 {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table2 {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table th,
                .custom-table td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .custom-table1 th,
                .custom-table1 td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .custom-table2 th,
                .custom-table2 td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .biaotou {
                  line-height: 5px;
                  text-align: center;
                }

                .title {
                  heigth: 5em;
                  line-height: 5em;
                  text-align: center;
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:center;
                  letter-spacing:4px;
                  font-weight:bold;
                  font-family:宋体;
                  font-size:24px;
                  opacity:1;
                  margin: 0 auto;
                  background:rgba(255, 255, 255, 0) !important;
                  border: 0 !important;
                  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
                }

                .span1 {
                  position: absolute;
                  bottom: 10px;
                  left: 0
                }
                .span2 {
                  position: absolute;
                  top: 10px;
                  right: 0
                }
              }
            </style>
          </head>
          <body>
             ${boxElement.outerHTML}
             <img id="chartImg">
            <script>
              window.onload = function() {
                window.print();
                window.close();
              }
            <\/script>
          </body>
          </html>
      `);
      if(this.yRadio != undefined) {
        console.log(this.dataUrls)
        this.dataUrls.forEach((item, index) => {
          const img = iframeDoc.createElement('img');
          img.src = item.dataUrl;
          iframeDoc.body.appendChild(img);
        })
      } else {
        const img = iframeDoc.getElementById('chartImg');
        img.src = this.dataUrl;
      }
      iframeDoc.close();
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-table {
  width: 100%; /* 设置表格宽度为100% */
  margin: 0 auto;
  border-collapse: collapse; /* 合并单元格边框 */
}

.custom-table1 {
  width: 100%; /* 设置表格宽度为100% */
  margin: 0 auto;
  border-collapse: collapse; /* 合并单元格边框 */
}

.custom-table2 {
  width: 100%; /* 设置表格宽度为100% */
  margin: 0 auto;
  border-collapse: collapse; /* 合并单元格边框 */
}

.custom-table th,
.custom-table td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.custom-table1 th,
.custom-table1 td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.custom-table2 th,
.custom-table2 td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.biaotou {
  line-height: 5px;
  text-align: center;
}

.title {
  heigth: 5em;
  line-height: 5em;
  text-align: center;
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:center;
  letter-spacing:4px;
  font-weight:bold;
  font-family:宋体;
  font-size:24px;
  opacity:1;
  margin: 0 auto;
  background:rgba(255, 255, 255, 0) !important;
  border: 0 !important;
  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
}

.span1 {
  position: absolute;
  bottom: 10px;
  left: 0
}
.span2 {
  position: absolute;
  top: 10px;
  right: 0
}
</style>
